from typing import Dict, Optional
from alibabacloud_dysmsapi20170525.client import Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysms_models

class SMSService:
    def __init__(self, access_key_id: str, access_key_secret: str, sign_name: str):
        """
        初始化SMS服务
        
        Args:
            access_key_id: 阿里云访问密钥ID
            access_key_secret: 阿里云访问密钥密码
            sign_name: 短信签名名称
        """
        self.client = self._create_client(access_key_id, access_key_secret)
        self.sign_name = sign_name

    def _create_client(self, access_key_id: str, access_key_secret: str) -> Client:
        """
        创建阿里云客户端
        """
        config = open_api_models.Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret
        )
        # 访问的域名
        config.endpoint = 'dysmsapi.aliyuncs.com'
        return Client(config)

    async def send_sms(
        self,
        phone_number: str,
        template_code: str,
        template_param: Optional[Dict[str, str]] = None
    ) -> bool:
        """
        发送短信
        
        Args:
            phone_number: 接收短信的手机号码
            template_code: 短信模板CODE
            template_param: 短信模板参数，字典格式
        
        Returns:
            bool: 发送是否成功
        """
        try:
            send_request = dysms_models.SendSmsRequest(
                phone_numbers=phone_number,
                sign_name=self.sign_name,
                template_code=template_code,
                template_param=str(template_param) if template_param else None
            )
            
            response = self.client.send_sms(send_request)
            
            # 判断是否发送成功
            return response.body.code == "OK"
        except Exception as e:
            print(f"发送短信失败: {str(e)}")
            return False

async def test_sms():
    """
    测试短信发送功能
    """
    try:
        from .config import SMS_CONFIG
        
        # 创建短信服务实例
        sms_service = SMSService(
            access_key_id=SMS_CONFIG["access_key_id"],
            access_key_secret=SMS_CONFIG["access_key_secret"],
            sign_name=SMS_CONFIG["sign_name"]
        )
        
        # 测试发送验证码短信
        test_phone = "13800138000"  # 替换为你的测试手机号
        test_template_code = "SMS_XXXXXXXX"  # 替换为你的短信模板CODE
        test_params = {
            "code": "123456"  # 测试验证码
        }
        
        result = await sms_service.send_sms(
            phone_number=test_phone,
            template_code=test_template_code,
            template_param=test_params
        )
        
        if result:
            print("测试短信发送成功！")
        else:
            print("测试短信发送失败！")
            
    except Exception as e:
        print(f"测试过程发生错误: {str(e)}")

if __name__ == "__main__":
    import asyncio
    # 运行测试函数
    asyncio.run(test_sms()) 